<template>
    <el-card class="box-card">
        <el-button type="primary" icon="Plus" @click="addPPClick">添加品牌</el-button>
        <el-table :data="tableData" border style="width: 100%" class="table">
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="tmName" label="品牌名称" />
            <el-table-column label="品牌LOGO">
                <template #default="{ row: { logoUrl } }">
                    <img class="table_img" :src="logoUrl" alt="" srcset="">
                </template>
            </el-table-column>
            <el-table-column label="品牌操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" icon="Edit" @click="upDateClick(row)"></el-button>
                    <el-popconfirm title="你确定要删除吗?" @confirm="confirm(row)">
                        <template #reference>
                            <el-button size="small" type="primary" icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 5, 9, 15]"
            layout="prev, pager, next, jumper,->, sizes, total" :total="total" @size-change="getTrademark()"
            @current-change="getTrademark" />

        <!-- 新增编辑框 -->
        <el-dialog v-model="dialogVisible" :title="trademarkInfo.id ? '修改品牌' : '添加品牌'" width="30%"
            :before-close="handleClose">
            <el-form ref="tradRef" :model="trademarkInfo" :rules="tradRules" label-width="120px" class="demo-ruleForm"
                size="large" status-icon>
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input v-model="trademarkInfo.tmName" />
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" :action="API.UP_FILE" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="addPPTrue">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { baseTrademark } from '@/api/product/trademark/index'
import { Returnrademark, Records, Records_Data, DataStr } from '@/api/product/trademark/type'
import { API, addUpdate, remove } from '@/api/product/trademark/index'
import type { FormRules, UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
// 页面加载调用
onMounted(() => {
    getTrademark()
})
// 第几页
const page = ref<number>(1)
// 每页多少条
const limit = ref<number>(3)
// 中页数
const total = ref<number>(0)
// table数据
let tableData = ref<Records>([])

// 获取品牌
const getTrademark = async (num = 1) => {
    page.value = num
    const data: Returnrademark = await baseTrademark(page.value, limit.value)
    if (data.code === 200) {
        tableData.value = data.data.records
        total.value = data.data.total
    }
}



// 对话框显影
const dialogVisible = ref<boolean>(false)
// 请求参数
const trademarkInfo = reactive<Records_Data>({
    logoUrl: "",
    tmName: "",
})

const addPPClick = () => {
    dialogVisible.value = true
}

// 验证规则
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
    //是当表单元素触发blur时候,会触发此方法
    //自定义校验规则
    value.trim().length >= 2 ? callBack() : callBack(new Error('品牌名称位数大于等于两位'))
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
    value ? callBack() : callBack(new Error('LOGO图片务必上传'))
}
const tradRules = reactive<FormRules<Records_Data>>({
    tmName: [
        //required:这个字段务必校验,表单项前面出来五角星
        //trigger:代表触发校验规则时机[blur、change]
        { required: true, trigger: 'blur', validator: validatorTmName }
    ],
    logoUrl: [
        { required: true, validator: validatorLogoUrl }
    ]

})
// 上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: DataStr) => {
    trademarkInfo.logoUrl = response.data
}
// 上传之间的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件大小小于4M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: "上传文件格式务必PNG|JPG|GIF"
        })
        return false;
    }
}
const tradRef = ref()

// 关闭对话框
const handleClose = () => {
    tradRef.value.resetFields()
    tradRef.value.clearValidate('tmName')
    tradRef.value.clearValidate('logoUrl')
    dialogVisible.value = false
}
// 确定添加
const addPPTrue = async () => {
    await tradRef.value.validate()
    const data: DataStr = await addUpdate(trademarkInfo)
    if (data.code === 200) {
        ElMessage({
            message: trademarkInfo.id ? '修改品牌成功' : '添加品牌成功',
            type: 'success',
        })
        getTrademark(trademarkInfo.id ? page.value : 1)
    } else {
        ElMessage({
            message: trademarkInfo.id ? '修改品牌失败' : '添加品牌失败',
            type: 'error',
        })
    }
    handleClose()

}

// 编辑
const upDateClick = (row: Records_Data) => {
    Object.assign(trademarkInfo, row)
    dialogVisible.value = true
}

// 删除
const confirm = async (row: Records_Data) => {
    const data = await remove(row.id)
    if (data.code === 200) {
        ElMessage({
            message: '删除品牌成功',
            type: 'success',
        })
        getTrademark(tableData.value.length <= 1 ? page.value - 1 : page.value)
    } else {
        ElMessage({
            message: '修改品牌失败',
            type: 'error',
        })
    }
}

</script>
<script lang="ts">
export default {
    name: 'Trademark'
}
</script>
<style scoped lang="scss">
.table {
    margin: 20px 0;

    .table_img {
        width: 50px;
        height: 50px;
    }
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>